package com.yao.config;

import com.yao.filter.CustomerCorsFilter;
import com.yao.handler.LoginAuthenticationFailureHandler;
import com.yao.handler.LoginAuthenticationSuccessHandler;
import com.yao.handler.MyAccessDenyHandler;
import com.yao.handler.MyAuthenticationEntryPoint;
import com.yao.mygranter.DingtalkAuthenticationProvider;
import com.yao.mygranter.DingtalkAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

@Configuration
//@Order(-1)
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    CustomerCorsFilter customerCorsFilter;
    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }


    @Autowired
    MyAccessDenyHandler myAccessDenyHandler;

    @Autowired
    MyAuthenticationEntryPoint myAuthenticationEntryPoint;

    @Autowired
    LoginAuthenticationSuccessHandler loginAuthenticationSuccessHandler;


    @Autowired
    LoginAuthenticationFailureHandler loginAuthenticationFailureHandler;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.authenticationProvider(dingtalkAuthenticationProvider);
//        http.csrf().disable();
//        http.authorizeRequests()
//                .antMatchers("/oauth/logout")
//                .permitAll();

        http.csrf().disable();
        http.authorizeRequests().antMatchers("/oauth/logout","/error","/login","/oauth/confirm_access").permitAll().antMatchers("/oauth/authorize").anonymous().anyRequest().authenticated().and().formLogin();
//                .and()

//         .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.httpBasic().disable();
        http.exceptionHandling().authenticationEntryPoint(myAuthenticationEntryPoint)
                .accessDeniedHandler(myAccessDenyHandler);
        http.addFilterBefore(customerCorsFilter, WebAsyncManagerIntegrationFilter.class);

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.formLogin().loginProcessingUrl("/login").successHandler(loginAuthenticationSuccessHandler).failureHandler(loginAuthenticationFailureHandler);



//        http.requestMatchers().antMatchers("/oauth/**")
//                .and()
//                .cors()
//                .and()
//                .csrf().disable();

//        ((HttpSecurity)((HttpSecurity)((ExpressionUrlAuthorizationConfigurer.AuthorizedUrl)http.authorizeRequests().anyRequest()).authenticated().and()).formLogin().and()).httpBasic();

    }



//    @Bean
//    CorsFilter corsFilter() {
//        CorsConfiguration configuration = new CorsConfiguration();
//        configuration.setAllowedOrigins(Arrays.asList("*"));
//        configuration.setAllowedMethods(Arrays.asList("*"));
//        configuration.setAllowedHeaders(Arrays.asList("*"));
//        configuration.setAllowCredentials(true);
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        source.registerCorsConfiguration("/**", configuration);
//        return new CorsFilter(source);
//    }
//

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(defaultAuthenticationProvider());
        auth.authenticationProvider(dingtalkAuthenticationProvider);

    }

    @Autowired
    DingtalkAuthenticationProvider dingtalkAuthenticationProvider;

    // 密码解析器
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();
    }
    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    PasswordEncoder passwordEncoder;
    public AuthenticationProvider defaultAuthenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder);
        return provider;
    }

    @Override
    @Bean("authenticationManagerBean")
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
